const http = require('http')

// 创建一个 发送 JSON 响应的函数
const sendJsonResponse = function (res, code, data, message) {
    res.writeHead(200, {
        'Content-Type': 'application/json; charset=utf-8'
    });

    const responseData = {
        code: code,
        data: data,
        message: message
    };
    res.end(JSON.stringify(responseData));
}

// 创建一个服务器
const server = http.createServer((req, res) => {
    // 简单的路由逻辑
    if (req.url === "/") {
        // 主页路由
        sendJsonResponse(res, 200, {
            msg: "欢迎来到Node.js后端！",
            nodeId: process.version,
            timestamp: new Date().toISOString(),
        }, "success");
    } else if (req.url === "/users") {
        // 用户列表路由 - 直接传入 code , data , message
        const users = [
            {id: 1, name: "Alice"},
            {id: 2, name: "egon"},
            {id: 3, name: "Bob"}
        ]

        sendJsonResponse(res, 200, {
            users: users,
            total: users.length,
        }, "获取列表成功")
    } else if (req.url === "/error") {
        // 错误实例路由 - 直接传入错误 code data message
        sendJsonResponse(res, 500, null, "这是一个错误消息")
    } else {
        // 404 路由
        res.writeHead(404, {
            'Content-Type': 'application/json; charset=utf-8'
        });

        const errorResponse = {
            code: 404,
            data: null,
            message: "Not Found"
        };

        res.end(JSON.stringify(errorResponse));
    }
});

const POST = 3000;
server.listen(POST, () => {
    console.log(`服务器已启动，访问 http://localhost:${POST}`)
    console.log(`尝试访问: http://localhost:${POST}/`);
    console.log(`尝试访问: http://localhost:${POST}/users`);
    console.log(`尝试访问: http://localhost:${POST}/error (查看错误响应)`);
})